<template>
  <!-- 活动订单审核列表 -->
  <main-content title="审核订单">
    <template #tab-bar>
      <el-radio-group v-model="currentTab" @change="handleTabChange">
        <el-radio-button plain :label="item.value" v-for="(item, index) in tabList" :key="index">{{
          `${item.label}（${item.count}）` }}
        </el-radio-button>
      </el-radio-group>
    </template>

    <template #search-bar>
      <SearchBar inline :default-show-more="false">
        <template #normal>
          <el-form-item label="订单号">
            <el-input v-model="form.orderNo" clearable placeholder="搜索订单号" />
          </el-form-item>
          <el-form-item label="客户手机号">
            <el-input v-model="form.userPhone" clearable placeholder="搜索客户手机号" />
          </el-form-item>
          <el-form-item label="订单来源">
            <el-input v-model="form.detail" clearable placeholder="搜索活动名称" />
          </el-form-item>
          <el-form-item label="下单时间">
            <el-date-picker v-model="orderTime" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间"
              :default-time="defaultTime1" />
          </el-form-item>
        </template>
        <template #button>
          <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>
            <el-button type="primary" @click="batchAudit">订单审核</el-button>
          </el-form-item>
        </template>
      </SearchBar>
    </template>
    <LayoutTable ref="actAuditListRef" url="/extensions/merchant/order/pageOrder" :setSearch="setSearch"
      disable-auto-height :param="{ ...form, ...businessData, verifyStep: verifyStep }"
      @selection-change="handleSelectionChange" :rowKey="(row: any) => {
        return String(row.id);
      }
        ">
      <el-table-column type="selection" :reserve-selection="true" width="55" />

      <el-table-column prop="orderNo" label="订单号" min-width="240" />
      <el-table-column label="审核状态" min-width="120">
        <template #default="{ row }">
          <span v-if="row.verifyStep == 1">待审核</span>
          <span v-if="row.verifyStep == 2">通过</span>
          <div v-if="[3, 4].includes(row.verifyStep)"><span v-if="row.verifyStep == 3">拒绝</span><span
              v-if="row.verifyStep == 4">拒绝并退款</span>
            <el-popover placement="right-end" :width="100" trigger="hover" :content="row.verifyReason">
              <template #reference>
                <el-icon>
                  <Tickets />
                </el-icon>
              </template>
            </el-popover>
          </div>
        </template>

      </el-table-column>
      <el-table-column label="订单来源" prop="detail" min-width="160"></el-table-column>
      <el-table-column label="用户ID" min-width="160">
        <template #default="{ row }">
          <span v-if="row.user">{{ row.user.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户唯一标识" min-width="180">
        <template #default="{ row }">
          <span v-if="row.user">{{ row.user.unionId }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="userPhone" label="客户手机号" min-width="150" />
      <el-table-column label="商品类型" min-width="120">
        <template #default="scope">
          {{ getProductType(scope.row.goodsType) }}
        </template>
      </el-table-column>
      <el-table-column prop="productName" label="规格名称" min-width="120" />
      <el-table-column prop="payOfCurrencyCount" label="支付积分" min-width="100" />
      <el-table-column prop="payOfMoney" label="支付金额" width="150">
        <template #default="scope">
          <div>
            {{ setMoneyConfig(scope.row.payOfMoney) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="处理时间" width="180">
        <template #default="{ row }">
          {{ dateFormat(row.auditTime) }}
        </template>
      </el-table-column>
      <el-table-column label="处理人" prop="checkUserName" min-width="120"></el-table-column>

      <el-table-column label="操作" align="center" fixed="right" min-width="100">
        <template #default="{ row }">
          <el-button v-has="['21101']" link type="primary"
            @click="$router.push(`/activity/order/list/detail?id=${row.id}`)">
            查看订单
          </el-button>
          <el-button v-if="row.verifyStep == 1" link type="primary" @click="auditOrder(row)">
            订单审核
          </el-button>
        </template>
      </el-table-column>
    </LayoutTable>
    <AuditFormDialog v-model="show" @confirm="handleConfirm" @close="handleClose" />

  </main-content>
</template>

<script setup lang="ts">
import { setMoneyConfig } from "@/utils";
import AuditFormDialog from "@/components/order/AuditFormDialog.vue"
import { merchantProductTypes } from "@/config/dictionary";
import { dateFormat } from "@/utils/filters";
import { getRecentWeekTime } from "@/utils/getRecentWeekTime";
import { orderAudit, orderAuditBatch, getOrderStatics } from "@/api/pointsMall";
const actAuditListRef = ref()
const currentTab = ref('1,2,3,4')
const setSearch = ref(Number());
const tabList = ref([{
  label: '全部订单',
  value: '1,2,3,4',
  count: 0
}, {
  label: '待审核',
  value: '1',
  count: 0
},
{
  label: '通过',
  value: '2',
  count: 0
}, {
  label: '拒绝',
  value: '3,4',
  count: 0
}])
const selectionList = ref([])

const form = reactive({
  orderNo: "",
  userPhone: "",
  status: '11',
  startTime: null,
  endTime: null,
  goodsName: null,
  goodsType: "",
  title: "",
  detail: "",
  createStartTime: getRecentWeekTime().startTime,
  createEndTime: getRecentWeekTime().endTime,
  queryInsIds: [],

});
const businessData = reactive({
  status: '11',
  businessType: "activity",
});
const currentRow = ref(null)
const auditType = ref('')
const show = ref(false)
const orderTime = ref("" as any);
//添加默认一周下单时间
orderTime.value = [getRecentWeekTime().startTime, getRecentWeekTime().endTime]
const defaultTime1 = reactive([
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59),
]); // '12:00:00', '08:00:00'
watch(orderTime, (val) => {
  /* ... */
  if (val) {
    form.createStartTime = String(new Date(val[0]).getTime());
    form.createEndTime = String(new Date(val[1]).getTime());
  } else {
    form.createStartTime = "";
    form.createEndTime = "";
  }
});
const verifyStep = ref('1, 2, 3, 4')
const handleTabChange = (tab: string) => {
  verifyStep.value = tab
}

const onSearch = () => {
  setSearch.value++;
}

const auditOrder = (row: any) => {
  currentRow.value = row
  auditType.value = 'single'
  show.value = true
}

const handleSelectionChange = (val: any) => {
  selectionList.value = val
}

//批量审核
const batchAudit = () => {
  if (!selectionList.value.length) {
    return ElMessage.warning('请选择需要审核的订单！')
  }
  if (selectionList.value.every(i => [2, 3, 4].includes(i.verifyStep))) {
    currentRow.value = null
    actAuditListRef.value.clearSelection()
    return ElMessage.warning('请选择需要审核的订单！')
  }
  auditType.value = 'batch'
  show.value = true
}
const getProductType = (_productType: string) => {
  return (
    merchantProductTypes.find((item) => item.value === _productType)?.label ??
    _productType
  );
};
const handleClose = () => {
  currentRow.value = null
  actAuditListRef.value.clearSelection()
}
const handleConfirm = async (form: { flag: number, reason: string }) => {
  //单个审核
  if (auditType.value == 'single') {
    const res = await orderAudit({
      orderId: currentRow.value.id,
      flag: form.flag,
      reason: form.reason,
      businessType: 'activity'
    })
    if (res.code == 200) {
      ElMessage.success('提交成功')
      currentRow.value = null
      show.value = false
      getOrderStaticsList()
      onSearch()
    } else {
      ElMessage.error(res.errorMsg)
    }

  }
  //批量审核
  if (auditType.value == 'batch') {
    const orderIds = selectionList.value.map(i => i.id)
    const res = await orderAuditBatch({
      orderIds: orderIds,
      flag: form.flag,
      reason: form.reason,
      businessType: 'activity'
    })
    if (res.code == 200) {
      ElMessage.success('提交成功')
      currentRow.value = null
      show.value = false
      actAuditListRef.value.clearSelection()
      getOrderStaticsList()
      onSearch()

    } else {
      ElMessage.error(res.errorMsg)
    }
  }
}
watch(form, () => {
  getOrderStaticsList()
})

const getOrderStaticsList = async () => {
  tabList.value.forEach(i => i.count = 0)
  let rs: any = await getOrderStatics({ ...businessData, ...form });
  if (rs.code === 200) {
    let all = 0
    rs.payload?.forEach((item: { count: number; status: any, verifyStep: string | null | number }) => {
      if (item.verifyStep) {
        all = all + item.count
      }
      tabList.value.forEach((el) => {

        if (item.verifyStep == el.value) {
          el.count = item.count;
        } else if (item.verifyStep == 3 && el.value == '3,4') {
          el.count = item.count;
        } else if (item.verifyStep == 4 && el.value == '3,4') {
          el.count = el.count + item.count;
        }
        else if (item.status == '11' && el.value == '1,2,3,4') {
          el.count = item.count;
        }
      });
    });
    const el = tabList.value.find(i => i.value = '1,2,3,4')
    el && (el.count = all)
  }
};

onMounted(() => {
  getOrderStaticsList();
});

</script>
<style lang="scss" scoped></style>